<template>

  <a-drawer
    :title="title"
    width=50%
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @close="handleCancel"
    cancelText="关闭"
    style="height: 100%;overflow: auto;padding-bottom: 53px;">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-col :md="24" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback label="归属经销商名">

            <a-input placeholder="经销商名称" readOnly :disabled="title=='编辑'"  @click="handleToCust" v-decorator="['custName', check.custCode]"/>

          </a-form-item>
          <CodeConfigModal
            modal-width="90%"
            :showCode="this.showCode"
            ref="CodeConfigModal"
            @ok="handelSaveOk">
          </CodeConfigModal>
        </a-col>

        <a-col :md="24" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="所属总仓"
            hasFeedback>
            <a-input
              v-decorator="['warehouseName', check.warehouseName]"
              placeholder="请选择所属总仓"
              :disabled="title=='编辑'"
              readOnly
              @click="handleCancel1"
            />
            <a-modal
              title="仓库列表"
              :width="800"
              rowKey="id"
              :visible="visible1"
              :confirmLoading="confirmLoading"
              @ok="handleOk1"
              @cancel="handleCancel1"
              cancelText="关闭">
              <a-table bordered :data-source="dataSurces3" :columns="totals" style="width:90%;margin: 0 auto"
                       :pagination="ipagination6" @change="handleTableChange"
                       :rowSelection="{selectedRowKeys: selectedRowKeys6,onChange: onSelectChange6, type:'radio'}">
                <!--                  -->
              </a-table>

            </a-modal>
          </a-form-item>
        </a-col>

        <a-col :md="24" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="商品"
            hasFeedback>
            <a-input
              v-decorator="['productName', check.productName]"
              placeholder="请选择商品"
              :disabled="title=='编辑'"
              readOnly
              @click="handleProduct"
            />
          </a-form-item>
        </a-col>

        <a-col :md="24" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="初期库存"
            hasFeedback>
            <a-input
              v-decorator="['num', check.num||{}]"
              :disabled="title=='编辑'"
              placeholder="请输入库存数量"
            />
          </a-form-item>
        </a-col>

        <a-col :md="24" :sm="24" v-if="title=='编辑'">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="调整值"
            hasFeedback>
            <a-input
              v-decorator="['useNum', check.useNum||{}]"
              placeholder="请输入调整值"
            />
          </a-form-item>
        </a-col>
      </a-form>

    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleOk" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
    <productList ref="productList" :multiple="false"  @productcontact="productscontact" ></productList>
  </a-drawer>
</template>

<script>
import CodeConfigModal from '@/components/cn-select-popup/CodeConfigModal'
import productList from './ProductList'
import { httpAction,postAction } from '@/api/manage'
import pick from 'lodash.pick'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import JImageUpload from '@/components/cn-form/JImageUpload'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JSelectUserByDep from '@/components/cn-select-popup/JSelectUserByDep'
import JSelectTerminal from '@/components/cn-select-popup/JSelectTerminal'

export default {
  name: 'stockModal',
  components: {
    JImageUpload,
    AFormItem,
    ATextarea,
    JTreeSelect,
    JSelectUserByDep,
    JSelectTerminal,
    CodeConfigModal,
    productList
  },
  data() {
    return {
      check:{
        custCode: {
          rules: [
            { required: true, message: '请选择经销商' }
          ]
        },
        warehouseName: {
          rules: [
            { required: true, message: '请选择仓库' }
          ]
        },
        productName: {
          rules: [
            { required: true, message: '请选择商品' }
          ]
        },
        num: {
          rules: [
            { required: true, message: '请输入初期库存' }
          ]
        },
        useNum: {
          rules: [
            { required: true, message: '请输入调整值' }
          ]
        },
      },
      selectedRowKeys6:[],
      disableSubmit:false,
      selectionRows6: [],
      ipagination6: {
        current: 1,
        size: "10",
        pageSizeOptions: ["10", "20", "30"],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      totals:[
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          fixed: 'left',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '仓库名称',
          dataIndex: 'warehouseName',
          align: 'center'
        },{
          title: '仓库编号',
          dataIndex: 'warehouseCode',
          align: 'center'
        },

      ],
      dataSurces3: [],
      visible1: false,
      custCode: '',
      custName: '',
      showCode: 4,
      terminalName: '',
      terminalCode: '',
      title: '操作',
      visible: false,
      selecttype: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,

      form: this.$form.createForm(this),

      validatorRules: {
        warehouseCode: {
          rules: [{
            required: true, message: '', trigger: 'submit'
          }]
        },
        warehouseName: {
          rules: [{
            required: true, message: '', trigger: 'submit'
          }]
        },
        warehouseType: {
          rules: [{
            required: true, message: '', trigger: 'submit'
          }]
        },
        status: {
          rules: [{
            required: true, message: '', trigger: 'submit'
          }]
        }
      },
      url: {
        add: window._CONFIG['domianURL'] + '/stock/cnStock/save',
        edit: window._CONFIG['domianURL'] + '/stock/cnStock/updateNum'
      },
      warehouse: window._CONFIG['domianURL'] + '/warehouse/cnWarehouse/findPageList'
    }
  },
  methods: {
    onSelectChange6(selectedRowKeys, selectionRows) {
      this.selectedRowKeys6 = selectedRowKeys;
      this.selectionRows6 = selectionRows;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.getWarehouse();
    },

    handleCancel1() {
      this.visible1=!this.visible1
    },

    handleOk1() {
      this.visible1=false
      this.form.setFieldsValue({
        warehouseName:this.selectionRows6[0].warehouseName,
        warehouseCode:this.selectionRows6[0].warehouseCode,
        warehouseType:this.selectionRows6[0].warehouseType
      })
      this.model.warehouseName=this.selectionRows6[0].warehouseName;
      this.model.warehouseCode=this.selectionRows6[0].warehouseCode;
      this.model.warehouseType=this.selectionRows6[0].warehouseType;
      // this.model.warehouseType_dictText=this.selectionRows6[0].warehouseType_dictText;
    },

    handleProduct(){
      this.$refs.productList.display=true;
      console.log(this.custCode)
      this.$refs.productList.visitproducts(this.custCode);
    },
    handelSaveOk(value) {
      this.custName = value.name
      this.custCode = value.code
      this.getWarehouse()
      this.form.setFieldsValue({
        custName : value.name,
        custCode : value.code
      })
      // this.model.custName = value.name
      // this.model.custCode = value.code
    },
    handleToCust() {
      this.$refs.CodeConfigModal.showModal()
      this.$refs.CodeConfigModal.title='选择经销商'
    },
    selects(value) {
      this.terminalName = value[0].terminalName
      this.terminalCode = value[0].terminalCode
    },
    dotype(val) {
      this.selecttype = val
    },
    add() {
      this.edit({})
    },
    edit(record) {
      console.log(record)
      // this.getWarehouse()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'warehouseCode', 'warehouseName',
          'warehouseType','custCode','custName','productName','num','id'))
      })
    },

    getWarehouse() {
      postAction(this.warehouse,{current:this.ipagination6.current,size:this.ipagination6.size,custCode:this.custCode}).then(res => {
        this.dataSurces3 = res.result.records
        // this.ipagination.total = res.result.total || 0;
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证

      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let formData = Object.assign(this.model, values)
          if (this.title == '新增') {
            httpurl += this.url.add
            formData.useType = 0
            formData.custCode=this.custCode
            formData.productCodeList=this.productCodeList
            formData.warehouseName=this.model.warehouseName
            formData.warehouseCode=this.model.warehouseCode
            formData.warehouseType=this.model.warehouseType
          } else if (this.title == '编辑') {
            httpurl += this.url.edit
            formData.useType = 1
          }
          //时间格式化
          //
          httpAction(httpurl, formData, 'post').then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },

    productscontact(e){
      let list=[]
      let name=[]
      e.map(v=> {
        list.push(v.productCode);
        name.push(v.productName);
      })
      this.form.setFieldsValue({
        productCodeList:list,
        productName:name+''
      })
      this.model.productName=name+''
      this.productCodeList=list
    }
  }
}
</script>

<style scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>